package com.ybwh.springboot1.util;

import org.springframework.util.PropertyPlaceholderHelper;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 占位符工具类
 */
public class PlaceholderUtil {
    private PlaceholderUtil() {
    }


    /**
     * <pre>
     *
     *  String pattern = "total {fishCount} fish, {deadCount} of which is dead!";
     *  Map<String,String> replaceRuler = new HashMap<>();
     *  replaceRuler.put("fishCount","15");
     *  replaceRuler.put("deadCount","0");
     *  System.out.print(PlaceholderUtil.format(pattern,replaceRuler));
     *
     * 输出结果：total 15 fish, 0 of which is dead!
     * </pre>
     *
     * @param pattern      占位符字符串,例如 "total {fishCount} fish, {deadCount} of which is dead!",
     *                     其中{fishCount}和{deadCount}就是占位符
     * @param replaceRuler 替换规则，key为占位符名称,value为替换内容
     * @return
     */
    public static String format(String pattern, Map<String, String> replaceRuler) {
        PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("{", "}");

        return propertyPlaceholderHelper.replacePlaceholders(pattern, new PropertyPlaceholderHelper.PlaceholderResolver() {
            @Override
            public String resolvePlaceholder(String placeholderName) {
                String value = replaceRuler.get(placeholderName);
                return value;
            }
        });
    }


    public static void main(String[] args) {
    	String pattern = "total {fishCount} fish, {deadCount} of which is dead!";
    	  Map replaceRuler = new HashMap<>();
    	  replaceRuler.put("fishCount","15");
    	  replaceRuler.put("deadCount","0");
    	  System.out.print(PlaceholderUtil.format(pattern,replaceRuler));

	}


}
